/*
    Copyright 2009 Barnet Wagman

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */
package ot;

import java.io.*;
import java.lang.reflect.*;

/**
 *
 * @author Barnet Wagman
 */
public class StandardSerializer implements Serializer {

        /**
         *
         * @return {@link ConstantsOt#SER}.
         */
    public String getObjectNameExtension() {
        return(ConstantsOt.SER);
    }

        /** {@inheritDoc}
         *
         * @param f
         * @param obj
         * @throws ot.OtException
         */
    public void objectToFile(File f, Serializable obj)
        throws OtException {
        try {
            FileOutputStream fos = new FileOutputStream(f);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(obj);
            // oos.flush();
                oos.reset();
            fos.close();
        }
        catch (java.io.IOException iox) {
            throw new OtException("Serialization.objectToFile(): "
                            + "error occurred writing object to file[]:"
                            + iox.toString());
        }
    } 

        /** {@inheritDoc}
         *
         * @param f
         * @return
         * @throws ot.OtException
         */
    public Object fileToObject(File f) throws OtException {

        try {
            FileInputStream fis = new FileInputStream(f);

            Object obj = new Object();
            ObjectInputStreamWithPrimitiveSupport oos
                    = new ObjectInputStreamWithPrimitiveSupport(fis);

            obj = oos.readObject();
            oos.close();

            return(obj);
        }
        catch(Exception xc) {             
            String mess;
            if ( f != null ) mess = f.getPath() + " exists? " + f.exists();
            else mess = " file is null";
            throw new OtException(mess + xc);
        }	
    } 
    
        /** Deserializes the object in the specified file.
         *
         *  This method creates and uses <tt>objectInputStreamClass</tt>
         *  as the object input stream class. <tt>objectStreamClass</tt>
         *  class must extend
         *  <tt>ObjectInputStream</tt>. This method does not use
         *  primitive support.
          *
          * @param f
          * @param objectInputStreamClass
          * @return
          * @throws ot.OtException
          */
    public Object fileToObject(File f, Class objectInputStreamClass)
        throws OtException {
        
        try {
            FileInputStream fis = new FileInputStream(f);
            Constructor c =                     
                objectInputStreamClass.getConstructor(
                            new Class[] { InputStream.class }); 
            ObjectInputStream ois = (ObjectInputStream)
                                c.newInstance(new Object[] { fis });   
            Object obj = ois.readObject();
            ois.close();
                        
	    return(obj);
            
        }
        catch(Exception x) {
            System.out.println(x.getMessage());           
            x.printStackTrace();
            throw new OtException(x);
        }
    }
        
    public class ObjectInputStreamWithPrimitiveSupport 
        extends ObjectInputStream {
        
        public ObjectInputStreamWithPrimitiveSupport(InputStream is) 
            throws IOException, StreamCorruptedException {
            super(is);
        }

        public Class resolveClass(ObjectStreamClass desc)
            throws ClassNotFoundException, IOException {             
            try {
                return super.resolveClass(desc);
            } catch (ClassNotFoundException e) {
                String nm = desc.getName();
                if (nm.equals("int")) return int.class;
                if (nm.equals("long")) return long.class;
                if (nm.equals("float")) return float.class;
                if (nm.equals("double")) return double.class;
                if (nm.equals("char")) return char.class;
                if (nm.equals("boolean")) return boolean.class;
                if (nm.equals("short")) return short.class;
                if (nm.equals("byte")) return byte.class;
                else /* check for other primitive types if one wishes.*/
                    throw e;
            }
        }
    }

        /** {@inheritDoc}
         *
         * @param obj
         * @return
         * @throws ot.OtException
         */
    public byte[] objectToByteArray(Serializable obj )
        throws OtException {

        try {                               
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();	 
	    ObjectOutputStream oos = new ObjectOutputStream(baos);
	    oos.writeObject(obj);            	        
        oos.reset();
        byte[] b = baos.toByteArray();
        baos = null;
        /* ^^^^^^^^ WARNING-Java BUG! when serializing large objects
         * the baos seems to leak memory.  When this method returns
         * baos is unreferenced and SHOULD get all its space freed up,
         * but it does not appear to, unless we explicitly null it out.
         */
        return(b);
	}        
        catch (java.io.IOException iox) {
                throw new OtException(iox);
        }
    } 

        /** Estimates the size of an object by serializing the
         *  object to a byte array and return the size of the array.
         *
         * @param x
         * @return
         * @throws ot.OtException
         */
    public int sizeInBytes(Serializable x) throws OtException {
        if ( x == null ) return(0);
        else return( objectToByteArray(x).length );
    }

        /** {@inheritDoc}
         * 
         * @param B
         * @return
         * @throws ot.OtException
         */
    public Object byteArrayToObject(byte[] B )
        throws OtException {
        try {
            ByteArrayInputStream baos = new ByteArrayInputStream(B,0,B.length);
            Object obj = new Object();
                ObjectInputStreamWithPrimitiveSupport oos
                    = new ObjectInputStreamWithPrimitiveSupport(baos);
            obj = oos.readObject();
            oos.close();
                baos = null;

            return(obj);
        }
        catch(InvalidClassException xc) { throw new OtException(xc); }
        catch ( java.io.IOException iox ) { throw new OtException(iox); }
        catch ( ClassNotFoundException cnfx ) { throw new OtException(cnfx); }
    }    
}
